#!/bin/bash
VERSION="1.1"

help() {
    echo "Version v"$VERSION
    echo "Usage:"
    echo "build.sh [-b] [-g] [-i input-file-path] [-o output-file-path]"
    echo "Description:"
    echo "-b: execute the sbt to build and copy the rvcpu.v"
    echo "-g: generate the binary file"
    echo "-m: the parameters when generating the binary file"
    echo "-s: run the verilator"
    echo "-d: enable difftest"
    echo "-f: bin-file used for the difftest"
    echo "-p: project name"
    echo "-a: difftest parameters"
    echo "-c: clean the vcd-files"
    echo "Commands examples:"
    echo './run.sh -g "-i ./czcpu/test3.txt  -o ./czcpu/test3.bin -m bin -r"'
    echo "./run.sh -d -b -s"
    exit 0
}

BUILD="false"
GENBIN="false"
MODEGEN="-i ./bin/test4.txt -o ./bin/test4-riscv64-mycpu.bin -m bin"
RUN="false"
DIFFTEST="false"
INSTBIN="inst_diff.bin"
PROJECT="czcpu_diff"
PARAMETER=" -b 0"
CLEAN="false"
WAVE=" "

ROOTDIR="../../../"
CLEANDIR="./projects/czcpu_diff/build"
BINSUFFIX="-riscv64-mycpu.bin"

# Check parameters
while getopts 'hbgm:sdf:p:a:cw' OPT; do
    case $OPT in
        h) help;;
        b) BUILD="true";;
        g) GENBIN="true";;
        m) MODEGEN="$OPTARG";;
        s) RUN="true";;
        d) DIFFTEST="true";;
        f) INSTBIN="$OPTARG";;
        p) PROJECT="$OPTARG";;
        a) PARAMETER=$OPTARG;;
        c) CLEAN="true";;
        w) WAVE="--dump-wave";;
        ?) help;;
    esac
done

# Clean the vcd files
if [[ "$CLEAN" == "true" ]]; then
    cd $CLEANDIR
    rm *.vcd
    cd $ROOTDIR
fi

# Build
if [[ "$BUILD" == "true" ]]; then
    cd ./cz-oscpu-chisel/

    if [[ "$DIFFTEST" == "true" ]]; then
        ./test.sh
    else
        ./run.sh
    fi

    cd ../
fi

# Generate the bin-file
if [[ "$GENBIN" == "true" ]]; then
    python BinGen.py $MODEGEN
fi

# Run the verilator
if [[ "$RUN" == "true" ]]; then
    if [[ "$DIFFTEST" == "true" ]]; then
        ./build.sh -e $PROJECT -d -b -s -a "-i $INSTBIN$BINSUFFIX $WAVE $PARAMETER" -m "EMU_TRACE=1"
    else
        ./build.sh -b -t rvcpu.v -s top.vcd
    fi
fi

